package mysql

import (
	"go.uber.org/zap"
	"struggle/model"
)

type userCountDAO struct{}

var DefaultUserCount = userCountDAO{}

// 创建用户时新增用户统计表
func (u userCountDAO) Create(userCount *model.UserCount) (err error) {
	sqlStr := `INSERT INTO st_user_count (uid) VALUES (?)`
	_, err = db.Exec(sqlStr, userCount.UID)
	if err != nil {
		zap.L().Error("Create userCount failed", zap.Error(err))
		return
	}
	return
}

func (u userCountDAO) FindOne(sn uint64) (userCount *model.UserCount, err error) {
	userCount = &model.UserCount{}
	sqlStr := `SELECT fans_num, follow_num, article_num, words, zan_num FROM st_user_count WHERE uid=? limit 1`
	err = db.Get(userCount, sqlStr, sn)
	if err != nil {
		zap.L().Error("get userCount failed", zap.Error(err))
		return
	}
	return
}

func (u userCountDAO) FindQuestions(sn uint64, offset, limit int) (questionList []*model.Question, err error) {
	sqlStr := `SELECT question_id, category_id, caption, content, author_id, create_time 
		FROM st_question WHERE author_id = ? order by id desc limit ?, ?`
	err = db.Select(&questionList, sqlStr, sn, offset, limit)
	if err != nil {
		zap.L().Error("get user questions list failed", zap.Error(err))
		return
	}
	return
}

func (u userCountDAO) FindAnswer(sn uint64, offset, limit int) (answerList *[]model.UserAnswerList, err error) {
	answerList = &[]model.UserAnswerList{}
	sqlStr := `SELECT *
		FROM st_answer INNER JOIN st_question ON st_answer.question_id = st_question.question_id
		WHERE st_answer.status=1 AND st_question.status=1 AND st_answer.author_id = ? 
		order by st_answer.id desc limit ?, ?`
	err = db.Select(answerList, sqlStr, sn, offset, limit)
	if err != nil {
		zap.L().Error("get user answers list failed", zap.Error(err))
		return
	}
	return
}

// 更新用户统计表的称赞字段数
func (u userCountDAO) UpdateZan(sn uint64, num int) (err error) {
	sqlStr := `UPDATE st_user_count SET zan_num=? WHERE uid=?`
	_, err = db.Exec(sqlStr, num, sn)
	if err != nil {
		zap.L().Error("update user_count zan failed", zap.Error(err))
		return
	}
	return
}
